package com.sky.websocket;



import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    // 保存所有在线的session
    private static ConcurrentHashMap<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    /**
     * 建立连接成功
     * @param session
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String sessionId = getSessionId(session);
        sessionMap.put(sessionId,session);
        System.out.println("连接成功:" + sessionId);
    }

    /**
     * 接收消息
     * @param session
     * @param message
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        System.out.println("客户端:" + getSessionId(session) + "发来了消息:  " + message.getPayload());
    }

    /**
     * 连接关闭
     * @param session
     * @param status
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessionMap.remove(getSessionId(session));
        System.out.println("连接关闭:" + getSessionId(session));
    }

    /**
     * 获取sessionId - 从URL路径中提取sid参数
     * @param session WebSocket会话
     * @return 从URL路径中提取的sid参数
     */
    private String getSessionId(WebSocketSession session) {
        // 从URL路径中提取sid参数
        return (String) session.getAttributes().get("sid");
    }

    /**
     * 消息群发
     */
    public void sendMessage(String message){
        Collection<WebSocketSession> sessions = sessionMap.values();
        for (WebSocketSession session : sessions) {
            try {
                if (session.isOpen()){
                    session.sendMessage(new TextMessage(message));
                }
            } catch (IOException e) {
                System.out.println("发送消息失败" + e.getMessage());
            }
        }
    }
}







